package com.anan.builder;

import com.anan.bean.FieldInfo;
import com.anan.bean.TableInfo;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class BuildMapper {

    // TableInfo{tableName='liabilities', beanName='Liabilities', comment='负债表',
    // fieldList=[FieldInfo{FieldName='id', propertyName='id', sqlType='varchar', javaType='String', comment='ID', isAutoIncrement=false}, FieldInfo{FieldName='user_id', propertyName='userId', sqlType='varchar', javaType='String', comment='用户id', isAutoIncrement=false}, FieldInfo{FieldName='time', propertyName='time', sqlType='varchar', javaType='String', comment='时间', isAutoIncrement=false}, FieldInfo{FieldName='name', propertyName='name', sqlType='varchar', javaType='String', comment='负债名称', isAutoIncrement=false}, FieldInfo{FieldName='quantity', propertyName='quantity', sqlType='double', javaType='Double', comment='金额', isAutoIncrement=false}, FieldInfo{FieldName='notes', propertyName='notes', sqlType='varchar', javaType='String', comment='备注', isAutoIncrement=false}, FieldInfo{FieldName='state', propertyName='state', sqlType='int', javaType='Integer', comment='1正常 0停用', isAutoIncrement=false}], keyIndexMap={PRIMARY=[FieldInfo{FieldName='id', propertyName='id', sqlType='varchar', javaType='String', comment='ID', isAutoIncrement=false}]}, haveDate=null, haveDateTime=null, haveBigDecimal=true}

    public static void createBaseMapper(String projectName) {
        String path = System.getProperty("user.dir") + "/" + projectName + "/src/main/java/com/anan/mapper";
        File file = new File(path);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (!mkdirs) {
                throw new RuntimeException("创建 " + path + " 目录失败");
            }
        }
        File beanFile = new File(path, "BaseMapper.java");
        OutputStream out = null;
        OutputStreamWriter outw = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(beanFile);
            outw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            bw = new BufferedWriter(outw);
            bw.write("package com.anan.mapper;\n" +
                    "\n" +
                    "import org.apache.ibatis.annotations.Param;\n" +
                    "\n" +
                    "import java.util.List;\n" +
                    "\n" +
                    "public interface BaseMapper<T,V> {  // t 为查询query  v为Do\n" +
                    "    Integer insert(@Param(\"query\") V query);\n" +
                    "    Integer insertBatch(@Param(\"list\") List<V> list);\n" +
                    "    Integer delete(@Param(\"query\") T query);\n" +
                    "    Integer update(@Param(\"query\") T query);\n" +
                    "    V get(@Param(\"query\") T query);\n" +
                    "    V getByFuzzyQuery(@Param(\"query\") T query);\n" +
                    "    List<V> list(@Param(\"query\") T query);\n" +
                    "    List<V> list();\n" +
                    "}\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != bw) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outw != null) {
                try {
                    outw.close();
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

    public static void createMapper(TableInfo tableInfo, String projectName) {
        createMapperXml(tableInfo, projectName);
        String beanName = tableInfo.getBeanName();
        String path = System.getProperty("user.dir") + "/" + projectName + "/src/main/java/com/anan/mapper";
        File file = new File(path);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (!mkdirs) {
                throw new RuntimeException("创建 " + path + " 目录失败");
            }
        }
        File beanFile = new File(path, beanName + "Mapper.java");
        OutputStream out = null;
        OutputStreamWriter outw = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(beanFile);
            outw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            bw = new BufferedWriter(outw);
            bw.write("package com.anan.mapper;\n" +
                    "\n" +
                    "import com.anan.entity.po." + beanName + ";\n" +
                    "import com.anan.entity.query." + beanName + "Query;\n" +
                    "\n" +
                    "public interface " + beanName + "Mapper extends BaseMapper<" + beanName + "Query, " + beanName + ">{\n" +
                    "}\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != bw) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outw != null) {
                try {
                    outw.close();
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

    private static void createMapperXml(TableInfo tableInfo, String projectName) {
        String beanName = tableInfo.getBeanName();
        String path = System.getProperty("user.dir") + "/" + projectName + "/src/main/resources/mapper";
        File file = new File(path);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (!mkdirs) {
                throw new RuntimeException("创建 " + path + " 目录失败");
            }
        }
        File beanFile = new File(path, beanName + "Mapper.xml");
        OutputStream out = null;
        OutputStreamWriter outw = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(beanFile);
            outw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            bw = new BufferedWriter(outw);
            bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                    "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\n" +
                    "        \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" +
                    "<mapper namespace=\"com.anan.mapper." + beanName + "Mapper\">\n" +
                    "\n" +
                    "    <!--实体映射-->\n" +
                    "    <resultMap id=\"result_map\" type=\"com.anan.entity.po." + beanName + "\">\n");

            // 结果映射集
            for (FieldInfo fieldInfo : tableInfo.getFieldList()) {
                bw.write("        <!--" + fieldInfo.getComment() + "-->\n" +
                        "        <result column=\"" + fieldInfo.getFieldName() + "\" property=\"" + fieldInfo.getPropertyName() + "\"/>\n");
            }
            bw.write("    </resultMap>\n\n\n");
            // 增
            bw.write("    <!-- 插入 （匹配有值的字段）-->\n" +
                    "    <insert id=\"insert\" parameterType=\"com.anan.entity.po." + beanName + "\">\n" +
                    "        INSERT INTO "+tableInfo.getTableName()+"\n" +
                    "        <trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">\n");
            for (FieldInfo fieldInfo : tableInfo.getFieldList()) {
                bw.write("            <if test=\"query."+fieldInfo.getPropertyName()+"!= null  and query."+fieldInfo.getPropertyName()+"!=''\">\n" +
                        "                "+fieldInfo.getFieldName()+",\n" +
                        "            </if>\n");
            }
            bw.write("        </trim>\n" +
                    "        <trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\">\n");
            for (FieldInfo fieldInfo : tableInfo.getFieldList()) {
                bw.write("            <if test=\"query."+fieldInfo.getPropertyName()+"!= null  and query."+fieldInfo.getPropertyName()+"!=''\">\n" +
                        "                #{query."+fieldInfo.getPropertyName()+"},\n" +
                        "            </if>\n");
            }
            bw.write("        </trim>\n" +
                    "    </insert>\n");
            //批量增加
            bw.write("    <!-- 添加 （批量插入）-->\n" +
                    "    <insert id=\"insertBatch\" parameterType=\"com.anan.entity.po."+beanName+"\">\n" +
                    "        INSERT INTO "+tableInfo.getTableName()+"(\n");
            for (FieldInfo fieldInfo : tableInfo.getFieldList()) {
                bw.write("        "+fieldInfo.getFieldName()+",\n");
            }
            bw.write("\t\t)values\n" +
                    "        <foreach collection=\"list\" item=\"item\" separator=\",\">\n" +
                    "            (\n");
            for (FieldInfo fieldInfo : tableInfo.getFieldList()) {
                bw.write("            #{item."+fieldInfo.getPropertyName()+"},\n");
            }
            bw.write("            )\n" +
                    "        </foreach>\n" +
                    "    </insert>\n");
            // 删
            bw.write("    <update id=\"delete\" parameterType=\"com.anan.entity.query."+beanName+"Query\">\n" +
                    "        update "+tableInfo.getTableName()+" set state = 0 where id=#{query.id}\n" +
                    "    </update>\n");
            bw.write("    <update id=\"deleteB\" parameterType=\"com.anan.entity.query."+beanName+"Query\">\n" +
                    "        delete from "+tableInfo.getTableName()+" where id=#{query.id}\n" +
                    "    </update>\n");
            // 改
            bw.write("    <!-- 根据Id修改-->\n" +
                    "    <update id=\"update\" parameterType=\"com.anan.entity.query."+beanName+"Query\">\n" +
                    "        UPDATE "+tableInfo.getTableName()+"\n" +
                    "        <set>\n");
            for (FieldInfo fieldInfo : tableInfo.getFieldList()) {
                bw.write("            <if test=\"query."+fieldInfo.getPropertyName()+"!= null  and query."+fieldInfo.getPropertyName()+"!=''\">\n" +
                        "                "+fieldInfo.getFieldName()+" = #{query."+fieldInfo.getPropertyName()+"},\n" +
                        "            </if>\n");
            }
            bw.write("        </set>\n" +
                    "             <where>\n" +
                        "            <if test=\"query.id!= null  and query.id!=''\">\n" +
                        "                and id = #{query.id}\n" +
                        "            </if>\n" +
                        "         </where>" +
                    "    </update>\n");
            //查 list
            bw.write("    <!-- 查询集合-->\n" +
                    "    <select id=\"list\" resultMap=\"result_map\">\n" +
                    "        SELECT * from "+tableInfo.getTableName()+"\n" +
                    "    </select>\n");
            // 查 get
            bw.write("      <select id=\"get\" resultMap=\"result_map\" parameterType=\"com.anan.entity.query."+beanName+"Query\">\n" +
                    "        select * from "+tableInfo.getTableName()+"\n" +
                    "        <where>\n" +
                    "            <if test=\"query.id!= null  and query.id!=''\">\n" +
                    "                and id = #{query.id}\n" +
                    "            </if>\n" +
                    "        </where>\n" +
                    "\n" +
                    "    </select>\n");
            // 查 getByFuzzyQuery
            bw.write("<select id=\"getByFuzzyQuery\" resultMap=\"result_map\" parameterType=\"com.anan.entity.query."+beanName+"Query\">\n" +
                    "        select * from "+tableInfo.getTableName()+"\n" +
                    "        <where>\n");
            for (FieldInfo fieldInfo : tableInfo.getFieldList()) {
                bw.write("            <if test=\"query."+fieldInfo.getPropertyName()+"!= null  and query."+fieldInfo.getPropertyName()+"!=''\">\n" +
                        "                and  "+fieldInfo.getPropertyName()+" like concat('%', #{query."+fieldInfo.getPropertyName()+"}, '%')\n" +
                        "            </if>\n");
            }
            bw.write("        </where>\n" +
                    "    </select>\n</mapper>\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != bw) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outw != null) {
                try {
                    outw.close();
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}

